package _03_栈;

import java.util.Stack;

public class _20_有效括号 {

    // 解题1
    public boolean isValid1(String s) {
        if (s.length() <= 0) return false;
        while (s.contains("()") || s.contains("{}") || s.contains("[]")) {
            s = s.replace("()", "");
            s = s.replace("{}", "");
            s = s.replace("[]", "");
        }
        return s.isEmpty();
    }


    // 解题2
    public boolean isValid(String s) {
        if (s.isEmpty()) return false;

        Stack<Character> list = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char curChar = s.charAt(i);
            if (curChar == '(' || curChar == '{' || curChar == '[') {
                // 左括号，进栈
                list.push(curChar);
            } else {
                // 右括号，比较
                if (list.isEmpty()) return false;
                char stackChar = list.peek();
                if ((stackChar == '(' && curChar == ')')
                        || (stackChar == '{' && curChar == '}')
                        || (stackChar == '[' && curChar == ']')) {
                    // 相等，出栈
                    list.pop();
                } else {
                    // 不相等，者括号不合法
                    return false;
                }
            }
        }
        return list.isEmpty();
    }


}
